package controllers

import (
	"encoding/json"
	"weiboxs.com/new_h_glasses/enums"
	"weiboxs.com/new_h_glasses/models"
	"weiboxs.com/new_h_glasses/services"
	"weiboxs.com/new_h_glasses/utils"
)

type ArchivesController struct {
	BaseController
}

func (c *ArchivesController) Prepare() {

	c.BaseController.Prepare()

	c.Data["activeSidebarUrl"] = "/archives/edit"
}

func (c *ArchivesController) Index() {
	c.checkAuthor("archives/index")
	c.Data["activeSidebarUrl"] = "/archives/index"

	c.display("", "archives/index_footerjs.html")
}

func (c *ArchivesController) DataGrid() {
	c.checkAuthor("archives/index")

	var params models.ArchivesQueryParam
	json.Unmarshal(c.Ctx.Input.RequestBody, &params)
	params.Deps = c.curUser.ExtendDepartmentList
	data, total := models.ArchivesPageList(&params)
	c.jsonDataTable(total, data)
}

func (c *ArchivesController) Delete() {

	c.checkAuthor("archives/delete")

	id, _ := c.GetInt64("id")
	if err := models.ArchivesDelete(id, c.curUser.DepartmentId); err != nil {
		c.jsonResult(enums.JRCodeFailed, err.Error(), "")
	}
	c.jsonResult(enums.JRCodeSucc, "删除成功", "")
}

func (c *ArchivesController) Edit() {

	c.checkAuthor("archives/edit") //需要权限控制

	//如果是POST请求，则由Save处理
	if c.Ctx.Input.IsPost() {
		c.Save()
	}
	var err error

	Id, _ := c.GetInt64(":id", 0)
	c.Data["childTitle"] = "档案"
	if Id > 0 {
		c.Data["childTitle"] = "档案"
	}
	m := &models.Archives{}

	if Id == 0 {

	} else {
		m, err = models.GetArchivesById(Id)
		if err != nil {
			c.pageError("数据无效，请刷新后重试")
		}
		if m.DepartmentId != c.curUser.DepartmentId {
			c.pageError("数据无效，请刷新后重试")
		}
	}
	c.Data["m"] = m

	c.display("", "archives/edit_footerjs.html", "shared/layout_dialog.html")
}


func (c *ArchivesController) Save() {

	var err error
	m := models.Archives{}
	//获取form里的值
	if err = c.ParseForm(&m); err != nil {
		c.jsonResult(enums.JRCodeFailed, "获取数据失败", m.Id)
	}
	m.Pinyin = utils.ConvertPinyin(m.Realname)
	if m.Id == 0 {
		m.CreatedBy = c.curUser.RealName
		m.UpdatedBy = c.curUser.RealName
		m.DepartmentId = c.curUser.DepartmentId

		if _, err = models.ArchivesAdd(&m); err != nil {
			c.jsonResult(enums.JRCodeFailed, "添加失败", m.Id)
		}
		sync_guahao := c.GetString("sync_guahao")
		if len(sync_guahao) > 0 {  //需要同步挂号
			c.guahao_save(m.Id)
		}
	} else {

		if mr, err := models.GetArchivesById(m.Id); err != nil {
			c.jsonResult(enums.JRCodeFailed, "获取数据失败", m.Id)
		} else {
			m.Status = mr.Status
			m.CreatedAt = mr.CreatedAt
			m.CreatedBy = mr.CreatedBy
			m.DepartmentId = c.curUser.DepartmentId
		}

		m.UpdatedBy = c.curUser.RealName
		if err = m.ArchivesEdit(); err != nil {
			c.jsonResult(enums.JRCodeFailed, "编辑失败", m.Id)
		}
	}
	c.jsonResult(enums.JRCodeSucc, "操作成功", m)
}

/**
验光档案查询
 */
func (c *ArchivesController) EditForOpt() {
	//如果是POST请求，则由Save处理
	if c.Ctx.Input.IsPost() {
		var err error
		m := new(models.Archives)
		//获取form里的值
		if err = c.ParseForm(m); err != nil {
			c.jsonResult(enums.JRCodeFailed, "获取数据失败"+err.Error(), "")
		}
		if len(m.Number) > 0 {
			m,err = models.GetArchivesByNumber(m.Number)
		}
		if err != nil || m.Id == 0 { //不存在
			m.CreatedBy = c.curUser.RealName
			m.UpdatedBy = c.curUser.RealName
			m.DepartmentId = c.curUser.DepartmentId
			if _, err = models.ArchivesAdd(m); err != nil {
				c.jsonResult(enums.JRCodeFailed, "添加失败", "")
			}
		}
		c.jsonResult(enums.JRCodeSucc, "ok", m)
	}

	var err error

	Id, _ := c.GetInt64(":id", 0)
	m := &models.Archives{}
	if Id == 0 {
	} else {
		m, err = models.GetArchivesById(Id)
		if err != nil {
			c.pageError("数据无效，请刷新后重试")
		}
		if m.DepartmentId != c.curUser.DepartmentId {
			c.pageError("数据无效，请刷新后重试")
		}
	}
	c.Data["m"] = m
	c.display("", "archives/editforopt_footerjs.html", "shared/layout_dialog.html")
}

//获取HIS用户信息
func (c *ArchivesController) GetHisUserInfo() {
	number := c.GetString("number")
	if(len(number) <= 0) {
		c.jsonResult(enums.JRCodeFailed, "就诊卡号不能为空", "")
	}
	ser := new(services.MssqlService)
	screening, err := ser.GetScreeningInfo(number, c.curUser)
	if(err != nil) {
		c.jsonResult(enums.JRCodeFailed, err.Error(), "")
	}
	c.jsonResult(enums.JRCodeSucc, "ok", screening)
}

func (c *ArchivesController) SelectArchives() {

	c.checkAuthor("archives/index") //直接给列表权限

	keyword := c.GetString("keyword")
	if c.Ctx.Input.IsPost() {

		var params models.ArchivesQueryParam
		params.Filter = keyword

		if count := models.ArchivesFilterCount(&params); count <= 0 {
			c.jsonResult(enums.JRCodeSucc, "没有重复记录", "")
		} else {
			c.jsonResult(enums.JRCodeFailed, "有重复记录", count)
		}
	}

	c.Data["keyword"] = keyword

	c.display("", "archives/selectarchives_footerjs.html", "shared/layout_dialog.html")
}



//查看单条档案数据,JSON返回
func (c *ArchivesController) ViewOne() {
	c.checkLogin()

	if c.Ctx.Input.IsPost() {
		arcId, _ := c.GetInt64(":id") //档案ID
		data, err := models.GetArchivesById(arcId)
		if err != nil {
			c.jsonResult(enums.JRCodeFailed, err.Error(), "")
		}
		c.jsonResult(enums.JRCodeSucc, "获取成功", data)
	}

	c.jsonResult(enums.JRCodeFailed, "获取指定参数出错！", "")
}

//获取最新关注的五条信息
func (c *ArchivesController) GetWechatFollows() {
	c.checkLogin()
	query := models.WechatFollowsQueryParam{}
	query.Limit = 10
	query.Offset = 0
	query.DepartmentId = c.curUser.DepartmentId
	lists := models.WechatFollowsList(&query)
	c.jsonResult(enums.JRCodeSucc, "ok", lists)
}

//获取配置信息
func (c *ArchivesController) getOption() (o map[string]interface{}) {

	o = make(map[string]interface{})

	f := models.OptionsQueryParam{}
	f.Status = "1"
	f.Depid = c.curUser.DepartmentId
	//获取医生
	f.Typeid = "10"
	o["doctor"] = models.OptionsList(&f)

	f.Typeid = "11"
	o["optometrist"] = models.OptionsList(&f)

	return
}

//销售记录
func (c *ArchivesController) retails(id int64) {

	c.display("archives/retails.html", "archives/retails_footerjs.html")
}
//新增随访
func (c *ArchivesController) followup(id int64) {

	c.display("archives/followup.html", "archives/followup_footerjs.html")
}

//获取问诊信息
func (c *ArchivesController) GetInterrogations() {
	id, _ := c.GetInt64(":id")
	if id == 0 {
		c.jsonResult(enums.JRCodeSucc, "参数传递错误", "")
	}

	data := models.InterrogationsView(id)

	c.jsonResult(enums.JRCodeSucc, "ok", data)
}

//保存问诊信息
func (c *ArchivesController) SaveInterrogations() {

	interrogations := new(models.Interrogations)

	//slice绑定
	c.Ctx.Input.Bind(&interrogations.BeforeConclusionSlice, "BeforeConclusion")
	c.Ctx.Input.Bind(&interrogations.BeforeTreatmentSlice, "BeforeTreatment")
	c.Ctx.Input.Bind(&interrogations.PastHistorySlice, "PastHistory")

	c.Ctx.Input.Bind(&interrogations.EnvironmentSlice, "Environment")
	c.Ctx.Input.Bind(&interrogations.RefractionOdSlice, "RefractionOd")
	c.Ctx.Input.Bind(&interrogations.RefractionOsSlice, "RefractionOs")

	c.Ctx.Input.Bind(&interrogations.AmblyopiaOdSlice, "AmblyopiaOd")
	c.Ctx.Input.Bind(&interrogations.AmblyopiaOsSlice, "AmblyopiaOs")
	c.Ctx.Input.Bind(&interrogations.ProposalSlice, "Proposal")

	c.Ctx.Input.Bind(&interrogations.InheritanceSlice, "Inheritance")

	if err := c.ParseForm(interrogations); err != nil {
		c.jsonResult(enums.JRCodeFailed, err.Error(), "")
	}
	arcid ,_ := c.GetInt64("Archives")
	archmodel := new(models.Archives)
	archmodel.Id = arcid
	interrogations.Archives = archmodel

	if err := models.InterrogationsSave(interrogations); err != nil {
		c.jsonResult(enums.JRCodeFailed, err.Error(), "")
	}
	c.jsonResult(enums.JRCodeSucc, "问诊保存成功", "")
}

//门诊挂号列表
func(c *ArchivesController) Guahao() {
	c.checkAuthor("archives/guahao")
	if c.Ctx.Input.IsPost() {
		query := models.DoGuahaoQueryParam{}
		json.Unmarshal(c.Ctx.Input.RequestBody, &query)
		query.DepartmentId = c.curUser.DepartmentId
		list,count := models.DoGuahaoPageList(&query)
		c.jsonDataTable(count, list)
	} else {
		c.Data["activeSidebarUrl"] = "/archives/guahao"
		c.display("", "archives/guahao_footerjs.html")
	}
}
//门诊挂号保存
func(c *ArchivesController) GuahaoSave() {
	c.checkAuthor("archives/guahao")
	archives_id,_ := c.GetInt64("archives_id")
	if archives_id == 0 {
		c.jsonResult(enums.JRCodeFailed, "参数错误", "")
	}
	if err := c.guahao_save(archives_id); err != nil {
		c.jsonResult(enums.JRCodeFailed, err.Error(), "")
	}
	c.jsonResult(enums.JRCodeSucc, "挂号成功", "")
}

//执行保存
func(c *ArchivesController) guahao_save(archives_id int64) error {
	model := new(models.DoGuahao)
	model.Archives = &models.Archives{Id:archives_id}
	model.CreatedBy = c.curUser.RealName
	model.DepartmentId = c.curUser.DepartmentId
	model.Status = 0
	if _, err := models.DoGuahaoSave(model); err != nil {
		return err
	}
	return nil
}

//门诊挂号退号
func(c *ArchivesController) GuahaoOut() {
	c.checkAuthor("archives/guahao")
	guahao_id,_ := c.GetInt64("id")
	if err := models.DoGuahaoOut(guahao_id); err != nil {
		c.jsonResult(enums.JRCodeFailed, err.Error(), "")
	}
	c.jsonResult(enums.JRCodeSucc, "退号成功", "")
}
